package hrms.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import hrms.dao.MainDao;

public class PageUtil<T> {
	
	public Result<List<T>> findByPage(String pages ,HttpServletResponse res,MainDao<T> dao,String message) {
		String deptId = "";
		int row = dao.findRow(); 
		if(message.startsWith("Emp")){
			deptId = message.substring(3);
			message = "Emp";
			
		}
		if(deptId != null && !"".equals(deptId)){
			int id  = Integer.parseInt(deptId);
			row = dao.findRowById(id);
		}
		
		Result<List<T>> result = new Result<List<T>>();
		int page = Integer.parseInt(pages);
		int size = 0;
		if(row>10){
			size = 10;
		} else if(row == 0){
			result.setStatus(1);
			result.setMsg("未找到数据");
			return result;
		} else {
			size = row;
		}
		int total = row / size;
		if (row % size != 0) {
			total++;
		}
		Cookie c1 = new Cookie(message+"Page",page+"");
		Cookie c2 = new Cookie(message+"Total",total+"");
		res.addCookie(c1);
		res.addCookie(c2);
		int start = (page-1)*size+1;
		int end = page*size;
		List<T> list = dao.findAll(start, end);
		if(deptId != null && !"".equals(deptId)){
			int id  = Integer.parseInt(deptId);
			list.clear();
			list = dao.findAllById(id ,start, end);
		}
		if(list.size()!=0){
			result.setStatus(0);
			result.setMsg("查询成功");
			result.setData(list);
		} else {
			result.setStatus(1);
			result.setMsg("未找到数据");
		}
		return result;
	}
	
	public static Result<Map<String, Integer>> pageTotal(HttpServletRequest req,String message){
		Cookie[] c = req.getCookies();
		String page = "1";
		String total = "1";
		for(Cookie cc : c){
			if(cc.getName().equals(message+"Page")){
				page = cc.getValue();
			}
			if(cc.getName().equals(message+"Total")){
				total = cc.getValue();
			}
		}
		Result<Map<String,Integer>> result = new Result<Map<String,Integer>>();
		Map<String,Integer> map = new HashMap<String,Integer>();
		map.put("page",Integer.parseInt(page));
		map.put("total",Integer.parseInt(total));
		if(map.get("page")!=null && map.get("total")!=null){
			result.setStatus(0);
			result.setMsg("page&total");
			result.setData(map);
		} else {
			result.setStatus(1);
			result.setMsg("获取page&total失败");
		}
		return result;
	}

	public static void main(String[] args) {
		String x = "123";
		System.out.println(x.substring(2));
	}
}
